package cn.yywd_123.Light;

/*
 *  Author: yywd_123
 *  Date: 2022/8/8
 */

import cn.yywd_123.Light.main.utils.CodeTransformer;
import javassist.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class ClassTransformer implements ClassFileTransformer {

	private static final Logger logger = LoggerFactory.getLogger(ClassTransformer.class.getName());
	private final CodeTransformer codeTransformer = new CodeTransformer();
	private final Instrumentation inst;

	public ClassTransformer(Instrumentation instrumentation) {
		inst = instrumentation;
		ClassPool.getDefault().importPackage("cn.yywd_123.Light.main.LightMain");
		ClassPool.getDefault().importPackage("cn.yywd_123.Light.command.CommandManager");

		ClassPool.getDefault().importPackage("org.lwjgl.opengl");
		ClassPool.getDefault().importPackage("org.lwjgl.input");
	}

	@Override
	public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
		className = className.replace('/', '.');//awa mcp正在反编译ok
		if (!className.startsWith("java") && !className.startsWith("openj9") && !className.startsWith("jdk") && !className.startsWith("sun") && !className.startsWith("com")) {
			try {
				CtClass ctClass = ClassPool.getDefault().makeClass(new ByteArrayInputStream(classfileBuffer));
				for (CtMethod method : ctClass.getDeclaredMethods()) codeTransformer.transformMethod(method);
				for (CtField field : ctClass.getDeclaredFields()) codeTransformer.transformField(className, field);

				/*if (className.equalsIgnoreCase("bhz") && AgentMain.getArg().contains("1.12")) {    //  1.12
					for (CtField field : ctClass.getDeclaredFields()) {
						switch (field.getName()) {
							case "an":
							case "ao":
							case "at": {
								field.setModifiers(Modifier.PUBLIC);
							}break;
						}
					}
				}*/
				return ctClass.toBytecode();
			} catch (IOException | CannotCompileException e) {
				e.printStackTrace();
				System.exit(1);
			}
		}
		return classfileBuffer;
	}
}
